package org.project.task.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.project.task.common.R;
import org.project.task.entity.Admin;
import org.project.task.common.Search;
import org.project.task.entity.User;
import org.project.task.service.AdminService;
import org.project.task.service.impl.UserServiceImpl;
import org.project.task.util.JwtUtils;
import org.project.task.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController extends BaseController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private PasswordUtil passwordUtil;
    @Autowired
    private UserServiceImpl userServiceImpl;

    @PostMapping("/getList")
    public R<Page<Admin>> getList(@RequestBody Search search) {
        System.out.println(search);
        try {
            Page<Admin> pageData = adminService.page(
                    getPage(),
                    new QueryWrapper<Admin>()
                            .like(StrUtil.isNotBlank(
                                            search.getContent()),
                                    "username",
                                    search.getContent()
                            )
                            .or()
                            .like(StrUtil.isNotBlank(
                                            search.getContent()),
                                    "name",
                                    search.getContent()
                            )
                            .orderByDesc("id")
            );
            return new R<Page<Admin>>().success(pageData);
        } catch (Exception e) {
            return new R<Page<Admin>>().error(e.getMessage());
        }
    }

    @GetMapping("/adminList")
    public R<List<Admin>> adminList() {
        R<List<Admin>> result = new R<>();
        List<Admin> adminList = adminService.list();
        if (adminList != null && !adminList.isEmpty()) {
            result.success(adminList);
        } else {
            result.error("查询对象不存在!");
        }
        return result;
    }

    @PostMapping("/login")
    public R<Admin> login(@RequestBody Admin admin) {
        R<Admin> result = new R<>();
        // 使用 md5 加密密码
        String encryptedPassword = passwordUtil.encryptPasswordByMd5(admin.getPassword());
        Admin admin_login = adminService.login(admin.getUsername(), encryptedPassword);
        // 是否存在该用户
        if (admin_login != null) {
            // 登录成功后生成token
            admin_login.setPassword(encryptedPassword);
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", admin_login.getUsername());
            String jwt = JwtUtils.generateJwt(claims);
            admin_login.setToken(jwt);
            result.success(admin_login);
            result.setMessage("登陆成功！");
        } else {
            result.error("用户不存在/密码错误!");
        }
        return result;
    }


    @GetMapping("/getById/{id}")
    public R<Admin> getById(@PathVariable("id") Integer id) {
        R<Admin> result = new R<>();
        Admin admin = adminService.getById(id);
        if (admin != null) {
            result.success(admin);
        } else {
            result.error("查询对象不存在!");
        }
        return result;
    }

    @PostMapping("/delete")
    public R<Admin> delete(@RequestBody List<Long> ids) {
        R<Admin> result = new R<>();
        if (adminService.removeByIds(ids)) {
            result.success("删除成功！");
        } else {
            result.error("删除失败！");

        }
        return result;
    }


    @PostMapping("/insert")
    public R<Admin> insert(@RequestBody Admin admin) {
        R<Admin> result = new R<>();
        if (admin != null) {
            if (admin.getPassword().isBlank() && admin.getPassword().isEmpty()) {
                // 使用 md5 加密密码
                String encryptedPassword = passwordUtil.encryptPasswordByMd5("888888");
                admin.setPassword(encryptedPassword);
            } else {
                String encryptedPassword = passwordUtil.encryptPasswordByMd5(admin.getPassword());
                admin.setPassword(encryptedPassword);
            }
            boolean rsg = adminService.save(admin);
            if (rsg) {
                result.success("添加成功！");
                result.setData(admin);
            } else {
                result.error("添加失败！");
            }
        } else {
            result.error("请传入正确参数！");
        }
        return result;
    }

    @PostMapping("/update")
    public R<Admin> update(@RequestBody Admin admin) {
        R<Admin> result = new R<>();
        if (admin != null) {
            Admin admin_ready = adminService.getById(admin.getId());
            if (!admin.getPassword().isEmpty() && !admin.getPassword().isBlank()) {
                // 使用 md5 加密密码
                String encryptedPassword = passwordUtil.encryptPasswordByMd5(admin.getPassword());
                admin.setPassword(encryptedPassword);
            } else {
                admin.setPassword(admin_ready.getPassword());
            }
            boolean rsg = adminService.updateById(admin);
            if (rsg) {
                result.success("修改成功！");
            } else {
                result.error("修改失败！");
            }
        } else {
            result.error("请传入正确参数！");
        }
        return result;
    }

    @GetMapping("/reset/{id}")
    public R<Admin> reset(@PathVariable("id") Integer id) {
        R<Admin> result = new R<>();
        Admin admin = adminService.getById(id);
        if (admin != null) {
            // 使用 md5 加密密码
            admin.setPassword(passwordUtil.encryptPasswordByMd5("888888"));
            boolean rsg = adminService.updateById(admin);
            if (rsg) {
                result.success("修改成功！");
            } else {
                result.error("修改失败！");
            }
        } else {
            result.error("请传入正确参数！");
        }
        return result;
    }
}
